package com.ihy.config;

import com.ihy.utils.ServiceStatusUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 监听并转发请求 使得tomcat支持https请求（需要安全证书支持）
 * http ---> https
 */
@Configuration
@Slf4j
public class HttpsConfig {
    //读取配置文件中的参数
    @Value("${http.port}")
    private Integer httpPort;
    @Value("${server.port}")
    private Integer httpsPort;
    @Value("${server.servlet.context-path}")
    public String projectName;

    /**
     * 监听转发http请求
     *
     * @return tomcat http请求转发
     */
    private Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        // Connector 监听的 http 的端口号
        connector.setPort(httpPort);
        connector.setSecure(true);
        // 监听到http的端口号后转向到的https的端口号
        connector.setRedirectPort(httpsPort);
        return connector;
    }

    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(httpConnector());
        return tomcat;
    }

    /**
     * 获取本机网络访问地址(项目主页地址)
     *
     * @return 本机和网络项目主页访问地址
     */
    @Bean(initMethod = "getLocalIP")
    public ServiceStatusUtil localIP() {
        //获取以太网ip
        List<String> localIP = ServiceStatusUtil.getLocalIP();
        for (String s : localIP) {
            if (s.equals("127.0.0.1") || s.equals("localhost")) {
                log.info("本机访问地址: {}   {}", "http://" + s + ":" + httpPort + projectName, "https://" + s + ":" + httpsPort + projectName);
            } else {
                log.info("网络访问地址: {}   {}", "http://" + s + ":" + httpPort + projectName, "https://" + s + ":" + httpsPort + projectName);
            }
        }
        return new ServiceStatusUtil();
    }
}